﻿using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using LiveWebServiceBase.ServiceUser;

namespace LiveWebService.IUV
{
    public class LiveIUV
    {
        private string _LiveID;
        private string _SharedSecretKey;

        public LiveIUV(User currentUser, string LiveID)
        {
            this._LiveID = LiveID;
            this._SharedSecretKey = currentUser.GetOrganizationByLiveID(LiveID).sharedsecretkey;

            if (ServicePointManager.ServerCertificateValidationCallback == null)
            {
                ServicePointManager.ServerCertificateValidationCallback +=
                    delegate(object objSender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
                    {
                        return true;
                    };
            }
        }

        public string GetIUVRedirectString(string userName, string shopperIP, string firstName, string lastName,
        string academicStatuses, string webstoreName)
        {
            string responseText;
            try
            {
                //responseText = AuthenticateUser();

                // Build the Authenticate user URL
                StringBuilder sb = new StringBuilder("https://e5.onthehub.com/WebStore/Security/AuthenticateUser.aspx");
                sb.AppendFormat("?username={0}", userName);
                sb.AppendFormat("&email={0}", _LiveID);
                sb.AppendFormat("&key={0}", this._SharedSecretKey);

                if (!String.IsNullOrEmpty(shopperIP))
                {
                    sb.AppendFormat("&shopper_ip={0}", shopperIP);
                }
                if (!String.IsNullOrEmpty(firstName))
                {
                    sb.AppendFormat("&first_name={0}", firstName);
                }
                if (!String.IsNullOrEmpty(lastName))
                {
                    sb.AppendFormat("&last_name={0}", lastName);
                }
                if (!String.IsNullOrEmpty(academicStatuses))
                {
                    sb.AppendFormat("&academic_statuses={0}", academicStatuses);
                }
                if (!String.IsNullOrEmpty(webstoreName))
                {
                    sb.AppendFormat("&webstore={0}", webstoreName);
                }

                // Generate and send the request to the authenticate user service.
                WebRequest request = WebRequest.Create(sb.ToString());

                // Do not catch any exceptions here as they will contain the error message and the caller must handle these exceptions.

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    responseText = reader.ReadToEnd();
                }

            }
            catch (WebException webEx)
            {
                // If the response is not successful then an exception will be thrown and we must can it and
                // read the error message.
                if (webEx.Response == null)
                {
                    throw new Exception(webEx.Message);
                }
                else
                {
                    throw new Exception(((HttpWebResponse)webEx.Response).StatusDescription);
                }
            }
            return responseText;
        }
    }
}